/**java config方式定义Bean
 */
package com.example.demospringbootbean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.*;
import org.springframework.core.io.ClassPathResource;

@ComponentScan
@Configuration
public class ClassConfiguration {
    @Bean(name="classA")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    @Description("Provides a basic example of a bean")
    @Lazy
    public ClassA getClassA(){
        ClassA classA=new ClassA();
        classA.setMessage("Inject by Java Configuration");
        return classA;
    }

    //构造器注入ClassC
    @Bean(name="classB2")
    public ClassB getClassB2(@Value("zhangsan") String name, @Value("20")int age, ClassC classC){
        AppContextUtil.printlng("java config方式构造器注入生成ClassB");
       return new ClassB(name,age,classC);
    }

    //setter注入ClassC，使用参数更加灵活，classC可以不在同一配置类中，如有多个实例可以用@Qualifier("xxx")修饰参数
    @Bean(name="classB3")
    public ClassB getClassB3(@Value("lisi") String name, @Value("30")int age,ClassC classC){
        ClassB classB=new ClassB();
        classB.setName(name);
        classB.setAge(age);
        classB.setClassC(classC);
        AppContextUtil.printlng("java config方式Setter注入生成ClassB");
        return classB;
    }

    @Bean     //不注明name时默认方法名为bean name
    public ClassB classB4(){
        ClassB classB=new ClassB();
        classB.setName("wangwu");
        classB.setAge(50);
        classB.setClassC(getClassC());   //getClassC()仅限于在统一配置类中
        AppContextUtil.printlng("java config方式Setter注入生成ClassB");
        return classB;
    }

    @Bean(name="classC")
    public ClassC getClassC(){
          return new ClassC();
//          return ClassCFactory1.getClassFromStaticFactory();           //静态工厂创建bean
//          return new ClassCFactory1().getClassFromInstanceFactory();   //实例工厂创建bean
    }

    //该方法虽然返回了xxxFactory , 但是Spring 会帮我们用这个类来创建 Class
//    @Bean
//    public ClassCFactory2 classCFactory2() {
//        return new ClassCFactory2();
//    }

//    @Bean
//    @ConfigurationProperties(prefix="my")
//    public ClassCollection classCollection(){
//        return new ClassCollection();
//    }

    @Bean
    public PropertiesFactoryBean myProperty(){
        PropertiesFactoryBean propertiesFactoryBean=new PropertiesFactoryBean();
        propertiesFactoryBean.setFileEncoding("UTF-8");
        propertiesFactoryBean.setLocation(new ClassPathResource("me.properties"));
        return propertiesFactoryBean;
    }

    @Bean YamlPropertiesFactoryBean myYamlProperty(){
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("me.yml"));
        return yaml;
    }
}
